﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Translator;
using Timer = System.Windows.Forms.Timer;

namespace Translator
{
    public partial class MainForm : Form
    {
        private NotifyIcon trayIcon;
        private ContextMenuStrip trayMenu;
        private TranslateService translateService;
        private readonly AppConfig _config;

        public MainForm(AppConfig config)
        {   
            _config = config;
            InitializeComponent();
            // 禁用最大化按钮
            this.MaximizeBox = false;

            // 设置固定边框样式
            this.FormBorderStyle = FormBorderStyle.Sizable;

            // 设置最大尺寸
            Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
            this.MaximumSize = new Size(workingArea.Width - 100, workingArea.Height - 100);

          
            InitializeTrayIcon();
            InitializeLanguageControls();
            translateService = new TranslateService(_config.BaiduTranslate.ApiKey,
            _config.BaiduTranslate.SecretKey);
            ApplyConfig();
        }

        private void ApplyConfig()
        {
            // 设置窗口初始状态
            if (_config.AppSettings.StartMinimized)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            }

            // 设置默认语言
            cmbFromLang.SelectedValue = _config.AppSettings.DefaultFromLanguage;
            cmbToLang.SelectedValue = _config.AppSettings.DefaultToLanguage;

            // 设置热键等...
        }

        private void InitializeTrayIcon()
        {
            // 创建托盘图标
            trayIcon = new NotifyIcon
            {
                Text = "翻译",
                Icon = new Icon("Resources/TS.ico"),
                Visible = true
            };

            // 创建上下文菜单
            trayMenu = new ContextMenuStrip();

            var showItem = new ToolStripMenuItem("显示翻译窗口", null, OnShowClicked);
            var exitItem = new ToolStripMenuItem("退出", null, OnExitClicked);

            trayMenu.Items.Add(showItem);
            trayMenu.Items.Add(new ToolStripSeparator());
            trayMenu.Items.Add(exitItem);

            trayIcon.ContextMenuStrip = trayMenu;
            trayIcon.DoubleClick += (sender, e) => BringWindowToFront();
        }

        private void InitializeLanguageControls()
        {
            var languages = new List<LanguageItem>
            {
                new LanguageItem("自动检测", "auto"),
                new LanguageItem("中文", "zh"),
                new LanguageItem("英语", "en"),
                new LanguageItem("日语", "jp"),
                new LanguageItem("韩语", "kor"),
                new LanguageItem("法语", "fra"),
                new LanguageItem("德语", "de"),
                new LanguageItem("西班牙语", "spa")
            };

            cmbFromLang.DataSource = new BindingSource(languages, null);
            cmbFromLang.DisplayMember = "Name";
            cmbFromLang.ValueMember = "Code";

            cmbToLang.DataSource = new BindingSource(languages.FindAll(x => x.Code != "auto"), null);
            cmbToLang.DisplayMember = "Name";
            cmbToLang.ValueMember = "Code";
            cmbToLang.SelectedIndex = 0; // 默认中文
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

        }

        private void OnShowClicked(object sender, EventArgs e)
        {
            ShowWindow();
        }

        private void BringWindowToFront()
        {
            // 如果窗口最小化，先恢复正常状态
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
            }

            // 激活窗口并置顶
            this.Show();
            this.TopMost = true;          // 先设置为置顶
            this.Activate();               // 激活窗口
            this.Focus();                  // 获取焦点
            this.TopMost = false;          // 取消置顶，但仍保持窗口在前

            // 对于某些系统需要额外调用
            SetForegroundWindow(this.Handle);
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private void ShowWindow()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.BringToFront();
            txtSource.Focus();
        }

        private void OnExitClicked(object sender, EventArgs e)
        {
            trayIcon.Visible = false;
            Application.Exit();
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_MAXIMIZE = 0xF030;

            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_MAXIMIZE)
            {
                // 完全阻止最大化
                return;
            }

            base.WndProc(ref m);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                return;
            }
            trayIcon?.Dispose();
            base.OnFormClosing(e);
        }

        private async void btnTranslate_Click(object sender, EventArgs e) 
        {
            if (string.IsNullOrWhiteSpace(txtSource.Text))
            {
                ShowStatusMessage("请输入要翻译的文本", StatusType.Warning);
                return;
            }

            try
            {
                btnTranslate.Enabled = false;
                ShowStatusMessage("翻译中...", StatusType.Info);

                string from = ((LanguageItem)cmbFromLang.SelectedItem).Code;
                string to = ((LanguageItem)cmbToLang.SelectedItem).Code;

                string result = await translateService.TranslateAsync(txtSource.Text, from, to);
                txtResult.Text = result;

                ShowStatusMessage("翻译完成", StatusType.Success);
            }
            catch (Exception ex)
            {
                ShowStatusMessage($"错误: {ex.Message}", StatusType.Error);
                txtResult.Text = string.Empty;
            }
            finally
            {
                btnTranslate.Enabled = true;
            }
        }

        private void ShowStatusMessage(string message, StatusType type)
        {
            statusLabel.Text = message;
            statusLabel.ForeColor = type switch
            {
                StatusType.Success => Color.Green,
                StatusType.Warning => Color.Orange,
                StatusType.Error => Color.Red,
                _ => Color.Black
            };

            // 3秒后自动清除
            var timer = new Timer { Interval = 3000 };
            timer.Tick += (s, e) => {
                statusLabel.Text = string.Empty;
                timer.Stop();
                timer.Dispose();
            };
            timer.Start();
        }

        private void txtSource_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && e.Control)
            {
                btnTranslate.PerformClick();
                e.SuppressKeyPress = true;
            }
        }

        private class LanguageItem
        {
            public string Name { get; }
            public string Code { get; }

            public LanguageItem(string name, string code)
            {
                Name = name;
                Code = code;
            }

            public override string ToString() => Name;
        }

        private enum StatusType { Info, Success, Warning, Error }
    }
}